import { http } from '@libs/common/request';
import { isPro } from '@libs/common/utils';

import { DeviceResult } from '@/constant.enum';

const host = `https://${
  isPro ? 'rms.hifenlei.com' : 'tsttrash.shencom.cn'
}/service-automat`;
const scid = isPro ? 'sc8820513B9B1903E4' : 'scEFDE4390209585C4';

const order = {
  deliver: host + '/api/terminal/order/deliver',
  show: host + '/api/terminal/order/show',
  light: host + '/api/terminal/light/adjust',
};

export interface RootObject<T = unknown> {
  data: T;
  errcode: string;
  errmsg: string;
}

interface IAtmDeliverBody {
  axisX: number;
  axisY: number;
  mcuid: string;
  /** 流水号 */
  transNo: string;

  /** 回调地址 */
  callback?: string;
}

export const ApiAtmDeliver = async (body: IAtmDeliverBody) => {
  try {
    const res = await http.post<RootObject>(
      order.deliver,
      {
        transNo: body.transNo,
        axisX: body.axisY, // 接口需要翻转
        axisY: body.axisX, // 接口需要翻转
        mcuid: body.mcuid,
      },
      { scid, Authorization: undefined },
    );

    if (res.data.errcode === '0000') {
      return body.transNo;
    } else {
      throw new Error(res.data.errmsg);
    }
  } catch (error) {
    throw error;
  }
};

export interface DeliverOrderDetail {
  axisX: number;
  axisY: number;
  callback: string;
  callbackCnt: number;
  callbackState: number;
  createdAt: string;
  desc: string;
  id: string;
  infrared: number;
  mcuid: string;
  result: (typeof DeviceResult)[number];
  scid: string;
  seq: number;
  state: number;
  transNo: string;
  type: number;
  updatedAt: string;
}

export const ApiAtmOrderShow = async (transNo: string, mcuid: string) => {
  try {
    const res = await http.post<RootObject<DeliverOrderDetail>>(
      order.show,
      { transNo, mcuid },
      { scid, Authorization: undefined },
    );

    if (res.data.errcode === '0000') {
      return res.data.data;
    } else {
      return null;
    }
  } catch (error) {
    console.log('失败:', error.message);
    return null;
  }
};

/**
 * 调整设备灯的亮度
 *
 * @param {number} bright 0-100
 * @return {*}
 */
export const ApiAtmLight = async (mcuid: string, bright: number) => {
  try {
    return http.post(
      order.light,
      { bright, mcuid },
      { scid, Authorization: undefined },
    );
  } catch (error) {
    console.log('失败:', error.message);
    return null;
  }
};
